import {
  ActionType,
  ProColumns,
  FooterToolbar,
  PageContainer,
  ProTable,
} from '@ant-design/pro-components';
import { Button, Divider, Input, InputNumber, message } from 'antd';
import { useRef, useState } from 'react';
import CreateForm from '@/components/CreateForm';
import services from '@/services/receivingOrder';
import MaterialWin from './components/material';
import ApprovesWin from './components/approves';
import React from 'react';


const { queryList, addData, modifyData, deleteData } = services.ReceivingOrderController

/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (id: number | string | null = null, fields: API.ReceivingOrder) => {
  const hide = message.loading('正在操作');
  try {
    console.log(fields)
    id ? await modifyData({ id }, { ...fields }) : await addData({ ...fields });
    hide();
    message.success('操作成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 *  删除节点
 * @param selectedRows
 */
const handleRemove = async (selectedRows: API.ReceivingOrder[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    await deleteData({
      id: selectedRows.find((row) => row.id)?.id || '',
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};
const ReceivingOrderList = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [winProps, setWindowProps] = useState<any>({ title: '新建', id: null, record: {}, width: 1200 })
  const [materialProps, setMaterialProps] = useState<any>({ modalVisible: false, title: '物料信息', id: null, width: 1000 })
  const [approveProps, setApproveProps] = useState<any>({ modalVisible: false, title: '审批信息', id: null, width: 1000 })
  const actionRef = useRef<ActionType>();
  const [selectedRowsState, setSelectedRows] = useState<API.ReceivingOrder[]>([]);
  const columns: ProColumns<API.ReceivingOrder>[] = [
    {
      title: '接收单号', dataIndex: 'receivingOrderNo', width: 100, ellipsis: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '单据说明', dataIndex: 'orderDescription', width: 100, ellipsis: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '打印日期', dataIndex: 'printDate', width: 100, ellipsis: true, valueType: 'dateTime',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '供应链订单号', dataIndex: 'supplyChainOrderNo', width: 100, ellipsis: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: 'ERP订单编号', dataIndex: 'erpOrderNo', width: 100, ellipsis: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '接收日期', dataIndex: 'receiveDate', width: 150, ellipsis: true, valueType: 'date',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '库存组织', dataIndex: 'inventoryOrg', width: 100, ellipsis: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '供应商', dataIndex: 'supplier', width: 100, ellipsis: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '实物签收日期', dataIndex: 'physicalReceiveDate', width: 100, ellipsis: true, valueType: 'date',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '仓库名称', dataIndex: 'warehouseName', width: 150, ellipsis: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },

    {
      title: '订单主体', dataIndex: 'orderSubject', width: 150, ellipsis: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '物资类型', dataIndex: 'materialType', width: 100, ellipsis: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '合同编码', dataIndex: 'contractCode', width: 100, ellipsis: true,
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '未税金额(元)', dataIndex: 'untaxedAmount', valueType: 'money', width: 150, ellipsis: true,
      renderFormItem: () => {
        return <InputNumber prefix="￥" style={{ width: '50%' }} />
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '税金(元)', dataIndex: 'taxAmount', valueType: 'money', width: 150, ellipsis: true,
      renderFormItem: () => {
        return <InputNumber prefix="￥" style={{ width: '50%' }} />
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '含税金额(元)', dataIndex: 'taxIncludedAmount', valueType: 'money', width: 150, ellipsis: true,
      renderFormItem: () => {
        return <InputNumber prefix="￥" style={{ width: '50%' }} />
      },
      formItemProps: {
        rules: [
          {
            required: true,
            message: '必填项',
          },
        ],
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      fixed: 'right',
      width: 280,
      render: (_, record) => (
        <>
          <a
            onClick={() => {
              setWindowProps({ ...winProps, title: '编辑', id: record.id, record, width: 1200 })
              handleModalVisible(true)
            }}
          >
            编辑
          </a>
          <Divider type="vertical" />
          <a onClick={() => {
            setMaterialProps({ ...materialProps, modalVisible: true, title: '物料信息', id: record.id, record, width: 1200 })
          }}>物料信息</a>
          <Divider type="vertical" />
          <a onClick={() => {
            setApproveProps({ ...approveProps, modalVisible: true, title: '审批信息', id: record.id, record, width: 1200 })
          }}>审批信息</a>
          <Divider type="vertical" />
          <a onClick={() => {
            window.open("/supply.html?id=" + record.id, "_blank");
          }}>导出预览</a>
        </>
      ),
    },
  ];

  return (
    <PageContainer
      header={{
        title: '乙供材料接收单',
      }}
    >
      <ProTable
        actionRef={actionRef}
        rowKey="id"
        search={false}
        scroll={{ x: 1800 }}
        toolBarRender={() => [
          <Button
            key="1"
            type="primary"
            onClick={() => {
              setWindowProps({ ...winProps, title: '新建', id: null, record: {}, width: 1200 })
              handleModalVisible(true)
            }}
          >
            新建
          </Button>,
        ]}
        request={async (params) => {
          const { data, success,total } = await queryList({
            ...params,
          });
          return {
            data: data || [],
            success,
            total
          };
        }}
        columns={columns}
        rowSelection={{
          type: 'radio',
          onChange: (_, selectedRows) => setSelectedRows(selectedRows),
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
              项&nbsp;&nbsp;
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            删除
          </Button>
          {/* <Button type="primary">批量审批</Button> */}
        </FooterToolbar>
      )}
      <CreateForm
        onCancel={() => {
          handleModalVisible(false)
        }}
        modalVisible={createModalVisible}
        {...winProps}
      >
        <ProTable<API.ReceivingOrder, API.ReceivingOrder>
          onSubmit={async (value) => {
            const success = await handleAdd(winProps.id, value);
            if (success) {
              handleModalVisible(false);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}

          rowKey="id"
          type="form"
          form={{
            initialValues: winProps.record,
            layout: 'inline',
            labelCol: { style: { width: 180, margin: 4 } },
            wrapperCol: { style: { margin: 4, minWidth: 300 }, span: 16 },
            labelAlign: 'left',
          }}
          columns={columns}
        />
      </CreateForm>
      <CreateForm
        onCancel={() => {
          setMaterialProps({})
        }}
        {...materialProps}
      >
        <MaterialWin id={materialProps.id} />
      </CreateForm>
      <CreateForm
        onCancel={() => {
          setApproveProps({})
        }}
        {...approveProps}
      >
        <ApprovesWin id={approveProps.id} />
      </CreateForm>
    </PageContainer>

  );
}

export default ReceivingOrderList;